package org.dut.community.controller.Interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.dut.community.entity.LoginTicket;
import org.dut.community.entity.User;
import org.dut.community.service.UserService;
import org.dut.community.util.CookieUtil;
import org.dut.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Slf4j
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;
    
    @Autowired
    private SecurityContextRepository securityContextRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler) throws Exception {
        // 从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");
        if (ticket != null) {
            LoginTicket loginTicket = userService.getLoginTicket(ticket);
            if (loginTicket != null && loginTicket.getStatus() == 0 &&
                    loginTicket.getExpired().after(new Date())) {
                // 把用户信息放到hostHolder中
                log.debug("把用户信息放到hostHolder中");
                User user = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(user);
                // 把用户信息放到securityContext中
                log.debug("把用户信息放到securityContext中");

                // 创建Spring Security的安全上下文实现
                SecurityContext context = new SecurityContextImpl();
                // 设置认证对象 基于用户名密码的认证令牌
                // 参数分别为：主体(用户对象)、凭证(密码)、权限集合
                context.setAuthentication(new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), userService.getAuthorities(user.getId())));
                // 将安全上下文设置到当前线程中（ThreadLocal）
                SecurityContextHolder.setContext(context);
                // 存入数据库
                securityContextRepository.saveContext(context, request, response);
            }
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null){
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex)
            throws Exception {
        hostHolder.clear();
    }
}